package com.uzai.console.service.md.mdactivity.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.enums.MdActivityStatusEnum;
import com.uzai.common.enums.MdRobotCmdKeyEnum;
import com.uzai.common.enums.PlatformTypeEnum;
import com.uzai.common.enums.RedisCacheKeyEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.dto.feign.turnlink.SimpleTurnLinkDto;
import com.uzai.console.dto.feign.turnlink.TbPrivilegeDto;
import com.uzai.console.dto.md.mdactivity.MdActivityCopyDto;
import com.uzai.console.dto.md.mdactivity.MdActivityDto;
import com.uzai.console.dto.md.mdactivity.MdActivityIdDto;
import com.uzai.console.dto.md.mdactivity.MdActivityQuery;
import com.uzai.console.dto.md.mdgoods.MdGoodsDto;
import com.uzai.console.dto.md.mdgoods.MdGoodsPwdConverDto;
import com.uzai.console.dto.md.mdgoods.MdGoodsTurnlinkDto;
import com.uzai.console.dto.tb.tbapi.TbkScTpwdConvertDto;
import com.uzai.console.entity.*;
import com.uzai.console.mapper.*;
import com.uzai.console.service.feign.UzaiTurnlinkFeignService;
import com.uzai.console.service.md.mdactivity.MdActivityService;
import com.uzai.console.service.md.mdrebotcmd.MdRobotCmdService;
import com.uzai.console.service.tb.tbapi.TbApiService;
import com.uzai.console.vo.feign.turnlink.SimpleTurnlinkVo;
import com.uzai.console.vo.feign.turnlink.TbPrivilegesVo;
import com.uzai.console.vo.md.mdactivity.MdActivityCopyUrlVo;
import com.uzai.console.vo.md.mdactivity.MdActivityVo;
import com.uzai.console.vo.md.mdgoods.MdGoodsTurnlinkVo;
import com.uzai.console.vo.md.mdgoods.MdGoodsVo;
import com.uzai.console.vo.tb.tbapi.TbkScTpwdConvertVo;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 免单活动
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class MdActivityServiceImpl implements MdActivityService {

    Logger logger = LoggerFactory.getLogger(MdActivityServiceImpl.class);

    @Autowired
    private MdActivityMapper mdActivityMapper;
    @Autowired
    private AlarmContacterMapper alarmContacterMapper;
    @Autowired
    private MdGoodsMapper mdGoodsMapper;
    @Autowired
    private MdConfigPlanMapper mdConfigPlanMapper;
    @Autowired
    private MdRobotCmdMapper mdRobotCmdMapper;
    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;
    @Autowired
    private TbTokenMapper tbTokenMapper;
    @Autowired
    private DeviceWechatInfoMapper deviceWechatInfoMapper;
    @Autowired
    private ConfigPlanMapper configPlanMapper;
    @Autowired
    private UzaiTurnlinkFeignService uzaiTurnlinkFeignService;
    @Autowired
    private MdRobotCmdService mdRobotCmdService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TljDetailMapper tljDetailMapper;
    @Autowired
    private TbApiService tbApiService;

    /**
     * 查询免单活动列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param mdActivityQuery
     * @return null
     */
    public Page<MdActivityVo> findMdActivityList(MdActivityQuery mdActivityQuery){
        //新建返回到页面的LIST对象
        List<MdActivityVo> mdActivityVoList = new ArrayList<>();

        //执行分页查询对象
        Page<MdActivity> page = new Page<>();
        mdActivityQuery.convert(page);
        ArrayList<MdActivity> mdActivityList =  mdActivityMapper.findByList(page, mdActivityQuery);
        if(mdActivityList != null && mdActivityList.size() > 0){
            for (MdActivity mdActivity : mdActivityList){
                MdActivityVo mdActivityVo = new MdActivityVo();
                BeanUtils.copyProperties(mdActivity, mdActivityVo);

                //免单指令转化成list
                if(StringUtils.isNotBlank(mdActivity.getCommands())){
                    try {
                        mdActivityVo.setCommandList(JSONObject.parseArray(mdActivity.getCommands(), String.class));
                    }catch (Exception e){

                    }
                }

                //加载商品列表
                List<MdGoodsVo> mdGoodsVoListList = new ArrayList<>();
                List<MdGoods> mdGoodsList = mdGoodsMapper.findListByActivityId(mdActivity.getId(), mdActivity.getMerId());
                if(mdGoodsList != null && mdGoodsList.size() > 0){
                    for (MdGoods mdGoods : mdGoodsList) {
                        MdGoodsVo mdGoodsVo = new MdGoodsVo();
                        BeanUtils.copyProperties(mdGoods, mdGoodsVo);

                        //判断商品id前缀是否为空，如果不为空，则拼接在前面
                        if(StringUtils.isNotBlank(mdGoods.getItemIdPrefix())){
                            String itemId = mdGoods.getItemIdPrefix() + "-" + mdGoods.getItemId();
                            mdGoodsVo.setItemId(itemId);
                        }else{
                            mdGoodsVo.setItemId(mdGoods.getItemId());
                        }

                        mdGoodsVo.setTklList(JSONObject.parseArray(mdGoods.getTkls(), String.class));
                        mdGoodsVo.setImgList(JSONObject.parseArray(mdGoods.getImgs(), String.class));
                        mdGoodsVoListList.add(mdGoodsVo);
                    }
                }
                mdActivityVo.setMdGoodsVoListList(mdGoodsVoListList);

                //活动状态
                Integer status = Tools.getInteger(mdActivity.getStatus());
                //开始时间
                Integer startTime = Tools.getInteger(mdActivity.getStartTime());
                //结束时间
                Integer endTime = Tools.getInteger(mdActivity.getEndTime());
                //当前时间
//                int now = DateUtil.getNowTime();
//                if(now < startTime){//未开始
//                    mdActivityVo.setStatus(0);
//                    mdActivityVo.setStatusName("未开始");
//                }else if(now >= endTime){//已结束
//                    mdActivityVo.setStatus(3);
//                    mdActivityVo.setStatusName("已结束");
//                }else{//在时间内，需要判断状态是暂停，还是运行中
//                    if(status.intValue() == 1){ //开启中
//                        mdActivityVo.setStatus(1);
//                        mdActivityVo.setStatusName("进行中");
//                    }else{
//                        mdActivityVo.setStatus(2);
//                        mdActivityVo.setStatusName("暂停中");
//                    }
//                }

                if(mdActivityVo.getStatus() != null){
                    MdActivityStatusEnum mdActivityStatusEnum = MdActivityStatusEnum.getById(mdActivityVo.getStatus());
                    if(mdActivityStatusEnum != null){
                        mdActivityVo.setStatusName(mdActivityStatusEnum.getDesc());
                    }
                }

                //配置方案
                MdConfigPlan mdConfigPlan = mdConfigPlanMapper.selectById(mdActivity.getConfigId(), mdActivity.getMerId());
                if(mdConfigPlan != null){
                    mdActivityVo.setConfigName(mdConfigPlan.getName());
                    if(mdConfigPlan.getData() != null){
                        try {
                            //活动场景（0-群组活动；1-私聊活动）
                            JSONObject jsonObject = JSONObject.parseObject(mdConfigPlan.getData());
                            mdActivityVo.setActivityScenes(jsonObject.getInteger("activityScenes"));
                        }catch (Exception e){

                        }
                    }
                }

                //触发指令
                String commands = mdActivity.getCommands();
                if(StringUtils.isNotBlank(commands)){
                    try {
                        List<String> commandList = JSONObject.parseArray(commands, String.class);
                        mdActivityVo.setCommandList(commandList);
                    }catch (Exception e){

                    }
                }

                //会员标签
                String userTags = mdActivity.getUserTags();
                if(StringUtils.isNotBlank(userTags)){
                    try {
                        List<Long> userTagsList = JSONObject.parseArray(userTags, Long.class);
                        mdActivityVo.setUserTagsList(userTagsList);
                    }catch (Exception e){

                    }
                }

                mdActivityVoList.add(mdActivityVo);
            }
        }

        //返回到页面分页对象
        Page<MdActivityVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(mdActivityVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询免单活动详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param mdActivityIdDto
     * @return null
     */
    public MdActivityVo findMdActivity(MdActivityIdDto mdActivityIdDto){
        if(mdActivityIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        MdActivity mdActivity = mdActivityMapper.selectById(mdActivityIdDto.getId(), mdActivityIdDto.getMerId());

        if(mdActivity == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该免单活动不存在");
        }

        MdActivityVo mdActivityVo = new MdActivityVo();
        BeanUtils.copyProperties(mdActivity, mdActivityVo);

        //免单指令转化成list
        if(StringUtils.isNotBlank(mdActivity.getCommands())){
            try {
                mdActivityVo.setCommandList(JSONObject.parseArray(mdActivity.getCommands(), String.class));
            }catch (Exception e){

            }
        }

        //活动状态
        Integer status = Tools.getInteger(mdActivity.getStatus());
        //开始时间
        Integer startTime = Tools.getInteger(mdActivity.getStartTime());
        //结束时间
        Integer endTime = Tools.getInteger(mdActivity.getEndTime());
        //当前时间
//        int now = DateUtil.getNowTime();
//        if(now < startTime){//未开始
//            mdActivityVo.setStatus(0);
//            mdActivityVo.setStatusName("未开始");
//        }else if(now >= endTime){//已结束
//            mdActivityVo.setStatus(3);
//            mdActivityVo.setStatusName("已结束");
//        }else{//在时间内，需要判断状态是暂停，还是运行中
//            if(status.intValue() == 1){ //开启中
//                mdActivityVo.setStatus(1);
//                mdActivityVo.setStatusName("进行中");
//            }else{
//                mdActivityVo.setStatus(2);
//                mdActivityVo.setStatusName("暂停中");
//            }
//        }

        if(mdActivityVo.getStatus() != null){
            MdActivityStatusEnum mdActivityStatusEnum = MdActivityStatusEnum.getById(mdActivityVo.getStatus());
            if(mdActivityStatusEnum != null){
                mdActivityVo.setStatusName(mdActivityStatusEnum.getDesc());
            }
        }

        //加载商品列表
        List<MdGoodsVo> mdGoodsVoListList = new ArrayList<>();
        List<MdGoods> mdGoodsList = mdGoodsMapper.findListByActivityId(mdActivity.getId(), mdActivity.getMerId());
        if(mdGoodsList != null && mdGoodsList.size() > 0){
            for (MdGoods mdGoods : mdGoodsList) {
                MdGoodsVo mdGoodsVo = new MdGoodsVo();
                BeanUtils.copyProperties(mdGoods, mdGoodsVo);

                //判断商品id前缀是否为空，如果不为空，则拼接在前面
                if(StringUtils.isNotBlank(mdGoods.getItemIdPrefix())){
                    String itemId = mdGoods.getItemIdPrefix() + "-" + mdGoods.getItemId();
                    mdGoodsVo.setItemId(itemId);
                }else{
                    mdGoodsVo.setItemId(mdGoods.getItemId());
                }

                mdGoodsVo.setTklList(JSONObject.parseArray(mdGoods.getTkls(), String.class));
                mdGoodsVo.setImgList(JSONObject.parseArray(mdGoods.getImgs(), String.class));
                mdGoodsVoListList.add(mdGoodsVo);
            }
        }
        mdActivityVo.setMdGoodsVoListList(mdGoodsVoListList);

        //配置方案
        MdConfigPlan mdConfigPlan = mdConfigPlanMapper.selectById(mdActivity.getConfigId(), mdActivity.getMerId());
        if(mdConfigPlan != null){
            mdActivityVo.setConfigName(mdConfigPlan.getName());
            if(mdConfigPlan.getData() != null){
                try {
                    //活动场景（0-群组活动；1-私聊活动）
                    JSONObject jsonObject = JSONObject.parseObject(mdConfigPlan.getData());
                    mdActivityVo.setActivityScenes(jsonObject.getInteger("activityScenes"));
                }catch (Exception e){

                }
            }
        }

        //触发指令
        String commands = mdActivity.getCommands();
        if(StringUtils.isNotBlank(commands)){
            try {
                List<String> commandList = JSONObject.parseArray(commands, String.class);
                mdActivityVo.setCommandList(commandList);
            }catch (Exception e){

            }
        }

        //会员标签
        String userTags = mdActivity.getUserTags();
        if(StringUtils.isNotBlank(userTags)){
            try {
                List<Long> userTagsList = JSONObject.parseArray(userTags, Long.class);
                mdActivityVo.setUserTagsList(userTagsList);
            }catch (Exception e){

            }
        }

        return mdActivityVo;
    }

    /**
     * 添加免单活动
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param mdActivityDto
     * @return null
     */
    @Transactional
    public void addMdActivity(MdActivityDto mdActivityDto){

        if(StringUtils.isBlank(mdActivityDto.getName())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入规则名称");
        }

        //活动类型
        Integer activityType = Tools.getInteger(mdActivityDto.getActivityType());
        //活动名称
        String name = Tools.getStr(mdActivityDto.getName());
        if(StringUtils.isBlank(name)){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入活动名称");
        }
        //活动图片
        String imgUrl = mdActivityDto.getImgUrl();
//        if(StringUtils.isBlank(imgUrl)){
//            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入活动图片");
//        }
        //触发指令
        List<String> commandList = mdActivityDto.getCommandList();
        //配置方案
        Long configId = mdActivityDto.getConfigId();
        if(configId == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择配置方案");
        }

        MdActivity mdActivity = new MdActivity();
        BeanUtils.copyProperties(mdActivityDto, mdActivity);

        //查询数据库最大得活动id
        Long maxActivityId = mdActivityMapper.findMaxActivityId();
        if(maxActivityId != null){ //数据库有，则递增+1
            maxActivityId = maxActivityId + 1;
        }else{ //数据库没有，则默认等于10000
            maxActivityId = 10000L;
        }
        //默认开启
        mdActivity.setStatus(MdActivityStatusEnum.NOT_START.getValue());
        Integer now = DateUtil.getNowTime();
        mdActivity.setId(IdWorker.getId());
        mdActivity.setSource(0); //默认私有活动
        mdActivity.setMerId(mdActivityDto.getMerId());
        mdActivity.setActivityId(maxActivityId);
        //触发指令
        mdActivity.setCommands(Tools.getStrEmpty(JSONObject.toJSONString(commandList)));
        //会员标签
        mdActivity.setUserTags(Tools.getStrEmpty(JSONObject.toJSONString(mdActivityDto.getUserTagsList())));
        mdActivity.setCreateTime(now);
        mdActivity.setUpdateTime(now);
        mdActivityMapper.insertSelective(mdActivity);

        //添加商品
        List<MdGoodsDto> mdGoodsDtoList = mdActivityDto.getMdGoodsDtoList();
        if(mdGoodsDtoList != null && mdGoodsDtoList.size() > 0){
            for (int i = 0; i < mdGoodsDtoList.size(); i++) {

                MdGoodsDto mdGoodsDto = mdGoodsDtoList.get(i);

                if(mdGoodsDto.getImgList() == null || mdGoodsDto.getImgList().size() == 0){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择商品图片");
                }

                if(StringUtils.isBlank(mdGoodsDto.getItemId())){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "商品id不能为空");
                }

                if(mdGoodsDto.getItemTitle() == null){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "商品标题不能为空");
                }

                MdGoods mdGoods = new MdGoods();
                BeanUtils.copyProperties(mdGoodsDto, mdGoods);
                mdGoods.setId(IdWorker.getId());
                mdGoods.setPlatform(Tools.getInteger(mdGoodsDto.getPlatform()));
                mdGoods.setMerId(mdActivityDto.getMerId());
                mdGoods.setActivityId(mdActivity.getId());
                mdGoods.setTkls(Tools.getStrEmpty(JSONObject.toJSONString(mdGoodsDto.getTklList())));
                mdGoods.setImgs(Tools.getStrEmpty(JSONObject.toJSONString(mdGoodsDto.getImgList())));
                mdGoods.setPrice(Tools.getDouble(mdGoodsDto.getPrice()));
                mdGoods.setFinalPrice(Tools.getDouble(mdGoodsDto.getFinalPrice()));
                mdGoods.setCouponVal(Tools.getDouble(mdGoodsDto.getCouponVal()));
                mdGoods.setReduction(Tools.getDouble(mdGoodsDto.getReduction()));
                mdGoods.setRedeemPoints(Tools.getInteger(mdGoodsDto.getRedeemPoints()));
                mdGoods.setMaxExchangeTotal(Tools.getInteger(mdGoodsDto.getMaxExchangeTotal()));
                mdGoods.setMaxPerPerson(Tools.getInteger(mdGoodsDto.getMaxPerPerson()));
                mdGoods.setCheckdrop(Tools.getInteger(mdGoodsDto.getCheckdrop()));
                mdGoods.setCheckdropforprice(Tools.getInteger(mdGoodsDto.getCheckdropforprice()));
                mdGoods.setDropstatus(Tools.getInteger(mdGoodsDto.getDropstatus()));
                mdGoods.setOrderRequire(Tools.getStr(mdGoodsDto.getOrderRequire()));
                mdGoods.setCreateTime(now+i); //根据创建时间来排序
                mdGoods.setUpdateTime(now+i);

                //请求转链最新的商品id
                MdGoodsTurnlinkDto mdGoodsTurnlinkDto = new MdGoodsTurnlinkDto();
                mdGoodsTurnlinkDto.setPlatform(mdGoodsDto.getPlatform());
                mdGoodsTurnlinkDto.setMerId(mdActivityDto.getMerId());
                mdGoodsTurnlinkDto.setItemId(mdGoodsDto.getItemId());
                mdGoodsTurnlinkDto.setMdConfigPlanId(configId);
                MdGoodsTurnlinkVo mdGoodsTurnlinkVo = getGoodsTurnlinkInfo(mdGoodsTurnlinkDto);
                if(mdGoodsTurnlinkVo == null){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "商品转链失败");
                }

                //设置最大佣金比例
                mdGoods.setMaxCommissionRate(mdGoodsTurnlinkVo.getMaxCommissionRate());

                String itemId = Tools.getStr(mdGoodsTurnlinkVo.getItemId());
                if(PlatformTypeEnum.PT_TAOBAO.getId().intValue() == mdGoodsTurnlinkDto.getPlatform().intValue()) {//淘宝商品
                    //判断是否有前缀
                    String[] itemIdArr = itemId.split("-");
                    if(itemIdArr != null && itemIdArr.length == 2){
                        mdGoods.setItemIdPrefix(itemIdArr[0]);
                        mdGoods.setItemId(itemIdArr[1]);
                    }else{
                        mdGoods.setItemId(itemId);
                    }
                }else{
                    mdGoods.setItemId(itemId);
                }

                mdGoodsMapper.insertSelective(mdGoods);

                //处理淘口令，判断是否采用淘口令
                if(mdActivityDto.getAwardModel() == 0){
                    if(mdActivityDto.getAmoygoldType() == 2){ //手动创建，必须要导入淘口令列表
                        if(mdGoodsDto.getTklList() != null && mdGoodsDto.getTklList().size() > 0){
                            //添加新的淘口令
                            for (String tkl : mdGoodsDto.getTklList()){
                                TljDetail tljDetail = tljDetailMapper.selectByPwdAndActivityId(tkl, mdActivity.getId(), mdActivity.getMerId());
                                if(tljDetail == null){
                                    tljDetail = new TljDetail();
                                    tljDetail.setId(IdWorker.getId());
                                    tljDetail.setMerId(mdActivity.getMerId());
                                    tljDetail.setActivityId(mdActivity.getId());
                                    tljDetail.setGoodsId(mdGoods.getId());
                                    tljDetail.setItemId(mdGoods.getItemId());
                                    tljDetail.setStatus(0); //默认有效未领取
                                    tljDetail.setCreateType(mdActivityDto.getAmoygoldType());
                                    tljDetail.setPwd(tkl);
                                    tljDetail.setCreateTime(now);
                                    tljDetail.setUpdateTime(now);

                                    //淘口令解析-2023-11-07号 屏蔽验证淘口令代码,
//                                    MdGoodsPwdConverDto mdGoodsPwdConverDto = new MdGoodsPwdConverDto();
//                                    mdGoodsPwdConverDto.setMerId(mdActivity.getMerId());
//                                    mdGoodsPwdConverDto.setMdConfigPlanId(mdActivity.getConfigId());
//                                    mdGoodsPwdConverDto.setPwd(tkl);
//                                    TbkScTpwdConvertVo tbkScTpwdConvertVo = tbkScTpwdConvert(mdGoodsPwdConverDto);
//                                    if(tbkScTpwdConvertVo != null){
//                                        tljDetail.setSendUrl(tbkScTpwdConvertVo.getOriginUrl());
//                                        if(tbkScTpwdConvertVo.getFlag() == 1){ //传入的pid和解析淘口令返回的pid相等，则此淘口令有效
//                                            tljDetail.setStatus(0); //有效
//                                        }
//                                    }
                                    tljDetailMapper.insertSelective(tljDetail);
                                }
                            }
                        }else{
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入淘口令");
                        }
                    }
                }

            }
        }

        //增加免单唤醒指令
        mdRobotCmdService.addMdRobotCmdForMdAtivity(mdActivityDto.getMerId(), mdActivity.getId(), MdRobotCmdKeyEnum.WAKEUPCMD.getKey(), commandList);
        //更新指令redis缓存
        List<MdRobotCmd> mdRobotCmdList = mdRobotCmdMapper.selectByMerId(mdActivityDto.getMerId());
        String data = Tools.getStrEmpty(JSONObject.toJSONString(mdRobotCmdList));
        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.MD_COMMAND_LIST.getKey(), mdActivityDto.getMerId()), data, 30, TimeUnit.DAYS);
    }

    /**
     * 修改免单活动
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param mdActivityDto
     * @return null
     */
    @Transactional
    public void updateMdActivity(MdActivityDto mdActivityDto){

        int now = DateUtil.getNowTime();

        if(mdActivityDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        if(StringUtils.isBlank(mdActivityDto.getName())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入免单活动名称");
        }

        //配置方案
        Long configId = mdActivityDto.getConfigId();
        if(configId == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择配置方案");
        }

        MdActivity mdActivity = mdActivityMapper.selectById(mdActivityDto.getId(), mdActivityDto.getMerId());

        if(mdActivity == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该免单活动不存在");
        }

        if(mdActivity.getStatus().intValue() != MdActivityStatusEnum.NOT_START.getValue()){
            if(configId.longValue() != mdActivity.getConfigId().longValue()){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "活动已开始，不能修改配置方案");
            }
        }

        //修改免单
        mdActivity.setSource(0); //默认私有活动
        mdActivity.setName(mdActivityDto.getName());
        mdActivity.setImgUrl(mdActivityDto.getImgUrl());
        mdActivity.setActivityType(mdActivityDto.getActivityType());
        mdActivity.setCommands(Tools.getStrEmpty(JSONObject.toJSONString(mdActivityDto.getCommandList())));
        //会员标签
        mdActivity.setUserTags(Tools.getStrEmpty(JSONObject.toJSONString(mdActivityDto.getUserTagsList())));
        mdActivity.setConfigId(configId);
        mdActivity.setAwardModel(mdActivityDto.getAwardModel());
        mdActivity.setAmoygoldType(mdActivityDto.getAmoygoldType());
        mdActivity.setLimitHours(mdActivityDto.getLimitHours());
        mdActivity.setLimitTimes(mdActivityDto.getLimitTimes());
        mdActivity.setStartTime(mdActivityDto.getStartTime());
        mdActivity.setEndTime(mdActivityDto.getEndTime());
        mdActivity.setUpdateTime(now);
        int j = mdActivityMapper.updateById(mdActivity);

        //修改成功
        if(j == 1){
            //临时保存编辑之后的活动商品信息，最后评论插入
            List<MdGoods> mdGoodsList = new ArrayList<>();

            List<MdGoodsDto> mdGoodsDtoList = mdActivityDto.getMdGoodsDtoList();
            if(mdGoodsDtoList != null && mdGoodsDtoList.size() > 0){
                for (int i = 0; i < mdGoodsDtoList.size(); i++) {
                    MdGoodsDto mdGoodsDto = mdGoodsDtoList.get(i);
                    if(mdGoodsDto.getImgList() == null || mdGoodsDto.getImgList().size() == 0){
                        throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择商品图片");
                    }

                    if(StringUtils.isBlank(mdGoodsDto.getItemId())){
                        throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "商品id不能为空");
                    }

                    if(mdGoodsDto.getItemTitle() == null){
                        throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "商品标题不能为空");
                    }

                    //需要新新插入的商品
                    MdGoods mdGoods = new MdGoods();
                    BeanUtils.copyProperties(mdGoodsDto, mdGoods);
                    mdGoods.setPlatform(Tools.getInteger(mdGoodsDto.getPlatform()));
                    mdGoods.setMerId(mdActivityDto.getMerId());
                    mdGoods.setActivityId(mdActivity.getId());
                    mdGoods.setPlatform(Tools.getInteger(mdGoodsDto.getPlatform()));
                    mdGoods.setTkls(Tools.getStrEmpty(JSONObject.toJSONString(mdGoodsDto.getTklList())));
                    mdGoods.setImgs(Tools.getStrEmpty(JSONObject.toJSONString(mdGoodsDto.getImgList())));
                    mdGoods.setPrice(Tools.getDouble(mdGoodsDto.getPrice()));
                    mdGoods.setFinalPrice(Tools.getDouble(mdGoodsDto.getFinalPrice()));
                    mdGoods.setReduction(Tools.getDouble(mdGoodsDto.getReduction()));
                    mdGoods.setRedeemPoints(Tools.getInteger(mdGoodsDto.getRedeemPoints()));
                    mdGoods.setMaxExchangeTotal(Tools.getInteger(mdGoodsDto.getMaxExchangeTotal()));
                    mdGoods.setMaxPerPerson(Tools.getInteger(mdGoodsDto.getMaxPerPerson()));
                    mdGoods.setCheckdrop(Tools.getInteger(mdGoodsDto.getCheckdrop()));
                    mdGoods.setCheckdropforprice(Tools.getInteger(mdGoodsDto.getCheckdropforprice()));
                    mdGoods.setDropstatus(Tools.getInteger(mdGoodsDto.getDropstatus()));
                    mdGoods.setOrderRequire(Tools.getStr(mdGoodsDto.getOrderRequire()));
                    mdGoods.setCreateTime(now + i);
                    mdGoods.setUpdateTime(now + i);

                    //请求转链最新的商品id
                    MdGoodsTurnlinkDto mdGoodsTurnlinkDto = new MdGoodsTurnlinkDto();
                    mdGoodsTurnlinkDto.setPlatform(Tools.getInteger(mdGoodsDto.getPlatform()));
                    mdGoodsTurnlinkDto.setMerId(mdActivityDto.getMerId());
                    mdGoodsTurnlinkDto.setItemId(mdGoodsDto.getItemId());
                    mdGoodsTurnlinkDto.setMdConfigPlanId(configId);
                    MdGoodsTurnlinkVo mdGoodsTurnlinkVo = getGoodsTurnlinkInfo(mdGoodsTurnlinkDto);
                    if(mdGoodsTurnlinkVo == null){
                        throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "商品转链失败");
                    }

                    //设置最大佣金比例
                    mdGoods.setMaxCommissionRate(mdGoodsTurnlinkVo.getMaxCommissionRate());

                    String itemId = Tools.getStr(mdGoodsTurnlinkVo.getItemId());
                    if(PlatformTypeEnum.PT_TAOBAO.getId().intValue() == mdGoodsTurnlinkDto.getPlatform().intValue()) {//淘宝商品
                        //判断是否有前缀
                        String[] itemIdArr = itemId.split("-");
                        if(itemIdArr != null && itemIdArr.length == 2){
                            mdGoods.setItemIdPrefix(itemIdArr[0]);
                            mdGoods.setItemId(itemIdArr[1]);
                        }else{
                            mdGoods.setItemId(itemId);
                        }
                    }else{
                        mdGoods.setItemId(itemId);
                    }

                    //如果没有商品id,则表示新增加商品，需要重新赋值id
                    if(mdGoods.getId() == null){
                        mdGoods.setId(IdWorker.getId());
                    }

                    if(mdGoodsDto.getId() != null){
                        MdGoods mdGoods_old = mdGoodsMapper.selectById(mdGoodsDto.getId(), mdActivityDto.getMerId());
                        if(mdGoods_old != null){//如果存在，则将旧的数据保存到新的字段当中
                            mdGoods.setId(mdGoods_old.getId());
                            mdGoods.setUsedCount(mdGoods_old.getUsedCount());
                            mdGoodsList.add(mdGoods);
                        }else {
                            mdGoods.setId(IdWorker.getId());
                            mdGoods.setUsedCount(0);
                            mdGoodsList.add(mdGoods);
                        }
                    }else{
                        mdGoods.setId(IdWorker.getId());
                        mdGoods.setUsedCount(0);
                        mdGoodsList.add(mdGoods);
                    }

                    //处理淘口令，判断是否采用淘口令
                    if(mdActivityDto.getAwardModel() == 0){
                        if(mdActivityDto.getAmoygoldType() == 2){ //手动创建，必须要导入淘口令列表
                            if(mdGoodsDto.getTklList() != null && mdGoodsDto.getTklList().size() > 0){
                                //先清除旧未领取的淘口令
                                tljDetailMapper.deleteNoUserByActivityId(mdActivity.getId(), mdActivity.getMerId());
                                //在添加新的淘口令
                                for (String tkl : mdGoodsDto.getTklList()){
                                    TljDetail tljDetail = tljDetailMapper.selectByPwdAndActivityId(tkl, mdActivity.getId(), mdActivity.getMerId());
                                    if(tljDetail == null){
                                        tljDetail = new TljDetail();
                                        tljDetail.setId(IdWorker.getId());
                                        tljDetail.setMerId(mdActivity.getMerId());
                                        tljDetail.setActivityId(mdActivity.getId());
                                        tljDetail.setGoodsId(mdGoods.getId());
                                        tljDetail.setItemId(mdGoods.getItemId());
                                        tljDetail.setStatus(0); //默认有效未领取
                                        tljDetail.setCreateType(mdActivityDto.getAmoygoldType());
                                        tljDetail.setPwd(tkl);
                                        tljDetail.setCreateTime(now);
                                        tljDetail.setUpdateTime(now);
                                        //淘口令解析-2023-11-07号 屏蔽淘口令验证功能
//                                        MdGoodsPwdConverDto mdGoodsPwdConverDto = new MdGoodsPwdConverDto();
//                                        mdGoodsPwdConverDto.setMerId(mdActivity.getMerId());
//                                        mdGoodsPwdConverDto.setMdConfigPlanId(mdActivity.getConfigId());
//                                        mdGoodsPwdConverDto.setPwd(tkl);
//                                        TbkScTpwdConvertVo tbkScTpwdConvertVo = tbkScTpwdConvert(mdGoodsPwdConverDto);
//                                        if(tbkScTpwdConvertVo != null){
//                                            tljDetail.setSendUrl(tbkScTpwdConvertVo.getOriginUrl());
//                                            if(tbkScTpwdConvertVo.getFlag() == 1){ //传入的pid和解析淘口令返回的pid相等，则此淘口令有效
//                                                tljDetail.setStatus(0); //有效
//                                            }
//                                        }
                                        tljDetailMapper.insertSelective(tljDetail);
                                    }
                                }
                            }else{
                                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入淘口令");
                            }
                        }
                    }
                }
            }

            //先删除商品，在添加商品
            mdGoodsMapper.deleteByActivityId(mdActivity.getId(), mdActivity.getMerId());

            //在批量插入商品
            if(mdGoodsList != null && mdGoodsList.size() > 0){
                mdGoodsMapper.batchAdd(mdGoodsList);
            }

            //添加免单触发唤醒指令
            List<String> commandList = mdActivityDto.getCommandList();
            //增加免单唤醒指令
            mdRobotCmdService.addMdRobotCmdForMdAtivity(mdActivityDto.getMerId(), mdActivity.getId(), MdRobotCmdKeyEnum.WAKEUPCMD.getKey(), commandList);
            //更新指令redis缓存
            List<MdRobotCmd> mdRobotCmdList = mdRobotCmdMapper.selectByMerId(mdActivityDto.getMerId());
            String data = Tools.getStrEmpty(JSONObject.toJSONString(mdRobotCmdList));
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.MD_COMMAND_LIST.getKey(), mdActivityDto.getMerId()), data, 30, TimeUnit.DAYS);
        }
    }

    /**
     * 删除
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param mdActivityIdDto
     * @return null
     */
    @Transactional
    public void deleteMdActivity(MdActivityIdDto mdActivityIdDto){
        if(mdActivityIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        MdActivity mdActivity = mdActivityMapper.selectById(mdActivityIdDto.getId(), mdActivityIdDto.getMerId());
        if(mdActivity == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该活动不存在");
        }

        mdActivityMapper.deleteById(mdActivityIdDto.getId(), mdActivityIdDto.getMerId());

        //删除商品
        mdGoodsMapper.deleteByActivityId(mdActivity.getId(), mdActivity.getMerId());

        //清除旧未领取的淘口令
        tljDetailMapper.deleteNoUserByActivityId(mdActivity.getId(), mdActivity.getMerId());

        //删除指令
        mdRobotCmdMapper.deleteByActivityId(mdActivity.getId(), mdActivity.getMerId());

        //更新指令redis缓存
        List<MdRobotCmd> mdRobotCmdList = mdRobotCmdMapper.selectByMerId(mdActivityIdDto.getMerId());
        String data = Tools.getStrEmpty(JSONObject.toJSONString(mdRobotCmdList));
        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.MD_COMMAND_LIST.getKey(), mdActivityIdDto.getMerId()), data, 30, TimeUnit.DAYS);
    }

    /**
     * 暂停免单活动
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param mdActivityIdDto
     * @return null
     */
    public void pauseMdActivity(MdActivityIdDto mdActivityIdDto){
        if(mdActivityIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        MdActivity mdActivity = mdActivityMapper.selectById(mdActivityIdDto.getId(), mdActivityIdDto.getMerId());

        if(mdActivity == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该免单活动不存在");
        }

        mdActivity.setStatus(MdActivityStatusEnum.PAUSE.getValue()); //暂停
        Integer now = DateUtil.getNowTime();
        mdActivity.setUpdateTime(now);
        mdActivityMapper.updateById(mdActivity);
    }

    /**
     * 开启免单活动
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param mdActivityIdDto
     * @return null
     */
    public void startMdActivity(MdActivityIdDto mdActivityIdDto){
        if(mdActivityIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        MdActivity mdActivity = mdActivityMapper.selectById(mdActivityIdDto.getId(), mdActivityIdDto.getMerId());

        if(mdActivity == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该免单活动不存在");
        }

        mdActivity.setStatus(MdActivityStatusEnum.START.getValue()); //开启
        Integer now = DateUtil.getNowTime();
        mdActivity.setStartTime(now);
        mdActivity.setUpdateTime(now);
        mdActivityMapper.updateById(mdActivity);
    }


    /**
     * 复制免单活动
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param mdActivityCopyDto
     * @return null
     */
    @Transactional
    public void copyMdActivity(MdActivityCopyDto mdActivityCopyDto){

        int now = DateUtil.getNowTime();

        if(mdActivityCopyDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        MdActivity mdActivity_old = mdActivityMapper.selectById(mdActivityCopyDto.getId(), mdActivityCopyDto.getMerId());

        if(mdActivity_old == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该免单活动不存在");
        }

        //活动名称
        String name_new = mdActivityCopyDto.getName();
        if(StringUtils.isBlank(name_new)){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入活动名称");
        }

        //开始时间
        Integer startTime_new = mdActivityCopyDto.getStartTime();
        if(startTime_new == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入活动开始时间");
        }
        //结束时间
        Integer endTime_new = mdActivityCopyDto.getEndTime();
        if(endTime_new == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入活动结束时间");
        }
        //旧活动id
        Long activityId_old = mdActivity_old.getId();
        //旧指令
        List<MdRobotCmd> robotCmdList_old = mdRobotCmdMapper.selectByActivityId(activityId_old, mdActivity_old.getMerId());
        //旧商品
        List<MdGoods> mdGoodsList_old = mdGoodsMapper.findListByActivityId(activityId_old, mdActivity_old.getMerId());

        //添加新活动
        MdActivity mdActivity_new  = new MdActivity();
        BeanUtils.copyProperties(mdActivity_old, mdActivity_new);
        //新的主键
        mdActivity_new.setId(IdWorker.getId());
        //新的活动id
        Long activityId_new = mdActivityMapper.findMaxActivityId();
        if(activityId_new != null){ //数据库有，则递增+1
            activityId_new = activityId_new + 1;
        }else{ //数据库没有，则默认等于10000
            activityId_new = 10000L;
        }
        mdActivity_new.setSource(Tools.getInteger(mdActivity_old.getSource())); //默认私有活动
        mdActivity_new.setActivityId(activityId_new);
        //新的开始时间
        mdActivity_new.setStartTime(startTime_new);
        //新的结束时间
        mdActivity_new.setEndTime(endTime_new);
        //新名称
        mdActivity_new.setName(name_new);
        mdActivity_new.setUpdateTime(now);
        mdActivity_new.setCreateTime(now);
        mdActivity_new.setStatus(MdActivityStatusEnum.NOT_START.getValue()); //未开启
        //清空指令
        mdActivity_new.setCommands("");
        //复制新的活动
        mdActivityMapper.insertSelective(mdActivity_new);

        //复制新的商品
        if(mdGoodsList_old != null && mdGoodsList_old.size() > 0){
            for (MdGoods mdGoods_old : mdGoodsList_old) {
                MdGoods mdGoods_new = new MdGoods();
                BeanUtils.copyProperties(mdGoods_old, mdGoods_new);
                mdGoods_new.setId(IdWorker.getId());
                mdGoods_new.setActivityId(mdActivity_new.getId());
                mdGoods_new.setCreateTime(now);
                mdGoods_new.setUpdateTime(now);
                mdGoods_new.setTkls(""); //清空淘口令
                mdGoods_new.setUsedCount(0);//清空已兑换数量
                mdGoodsMapper.insertSelective(mdGoods_new);
            }
        }

//        //复制新的指令
//        if(robotCmdList_old != null && robotCmdList_old.size() > 0){
//            List<MdRobotCmd> mdRobotCmdList_new = new ArrayList<>();
//            for (MdRobotCmd mdRobotCmd_old : robotCmdList_old) {
//                MdRobotCmd mdRobotCmd_new = new MdRobotCmd();
//                BeanUtils.copyProperties(mdRobotCmd_old, mdRobotCmd_new);
//                mdRobotCmd_new.setId(IdWorker.getId());
//                mdRobotCmd_new.setActivityId(activityId_new);
//                mdRobotCmd_new.setCreateTime(now);
//                mdRobotCmd_new.setUpdateTime(now);
//                mdRobotCmdList_new.add(mdRobotCmd_new);
//            }
//            //批量复制新指令
//            mdRobotCmdMapper.batchAdd(mdRobotCmdList_new);
//        }
    }

    /**
     * 复制链接
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param mdActivityIdDto
     * @return null
     */
    public MdActivityCopyUrlVo copyUrl(MdActivityIdDto mdActivityIdDto){
        if(mdActivityIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        MdActivity mdActivity = mdActivityMapper.selectById(mdActivityIdDto.getId(), mdActivityIdDto.getMerId());

        if(mdActivity == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该免单活动不存在");
        }

        MdActivityVo mdActivityVo = new MdActivityVo();
        BeanUtils.copyProperties(mdActivity, mdActivityVo);

        MdActivityCopyUrlVo mdActivityCopyUrlVo = new MdActivityCopyUrlVo();
        mdActivityCopyUrlVo.setUrl(mdActivityVo.getActivityUrl());
        return mdActivityCopyUrlVo;
    }

    /**
     * 获取商品转链信息
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param mdGoodsTurnlinkDto
     * @return null
     */
    public MdGoodsTurnlinkVo getGoodsTurnlinkInfo(MdGoodsTurnlinkDto mdGoodsTurnlinkDto){

        if(mdGoodsTurnlinkDto.getPlatform() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入商品平台");
        }

        if(StringUtils.isBlank(mdGoodsTurnlinkDto.getItemId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "商品id或链接不存在");
        }

        if(mdGoodsTurnlinkDto.getMdConfigPlanId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请上传免单配置方案id");
        }

        MdConfigPlan mdConfigPlan = mdConfigPlanMapper.selectById(mdGoodsTurnlinkDto.getMdConfigPlanId(), mdGoodsTurnlinkDto.getMerId());
        if(mdConfigPlan == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "选择的免单配置方案不存在");
        }

        MdGoodsTurnlinkVo mdGoodsTurnlinkVo = new MdGoodsTurnlinkVo();

        Long tbTokenId = null;
        String tbPid = "";
        Long pddTokenId = null;
        Long dyTokenId = null;
        Long ksTlbTokenId = null;

        //淘宝token
        JSONObject jsonObject = JSONObject.parseObject(mdConfigPlan.getData());
        if (jsonObject != null) {
            tbTokenId = jsonObject.getLong("tbTokenId");
            tbPid = jsonObject.getString("tbPid");
            pddTokenId = jsonObject.getLong("pddTokenId");
            dyTokenId = jsonObject.getLong("dyTokenId");
            ksTlbTokenId = jsonObject.getLong("ksTlbTokenId");
        }

        SimpleTurnLinkDto simpleTurnLinkDto = new  SimpleTurnLinkDto();
        simpleTurnLinkDto.setMerId(mdGoodsTurnlinkDto.getMerId());
        simpleTurnLinkDto.setGenerateShortUrl(0);

        UzaiRespVo<SimpleTurnlinkVo> uzaiRespVo = null;

        if(PlatformTypeEnum.PT_TAOBAO.getId().intValue() == mdGoodsTurnlinkDto.getPlatform().intValue()) {//淘宝
            if(tbTokenId == null || StringUtils.isBlank(tbPid)){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "免单配置方案中未配置淘宝联盟和pid");
            }

            //判断输入得是商品id还是商品链接
            if(mdGoodsTurnlinkDto.getItemId().contains("http")){//商品链接
                simpleTurnLinkDto.setUrl(mdGoodsTurnlinkDto.getItemId());
            }else{
                //先查找淘宝id
                String itemId = Tools.findTbItemIdByRegex(mdGoodsTurnlinkDto.getItemId());
                if(StringUtils.isNotBlank(itemId)){
                    simpleTurnLinkDto.setItemId(mdGoodsTurnlinkDto.getItemId());
                }else{
                    //查找淘口令，找到通过淘口令转链
                    String pwd = Tools.findTbPwdByRegex(mdGoodsTurnlinkDto.getItemId());
                    if(StringUtils.isNotBlank(pwd)){
                        simpleTurnLinkDto.setPwd(pwd);
                    }else{ //最后则默认为商品id
                        simpleTurnLinkDto.setItemId(mdGoodsTurnlinkDto.getItemId());
                    }
                }
            }

            simpleTurnLinkDto.setTokenId(tbTokenId);
            simpleTurnLinkDto.setPid(tbPid);
            uzaiRespVo = uzaiTurnlinkFeignService.tbTurnlinkSimple(simpleTurnLinkDto);

            logger.info("---调用淘宝商品转链- 参数={}，返回结果={}",JSONObject.toJSONString(simpleTurnLinkDto),JSONObject.toJSONString(uzaiRespVo));

        }else if(PlatformTypeEnum.PT_PDD.getId().intValue() == mdGoodsTurnlinkDto.getPlatform().intValue()) { //拼多多
            if(pddTokenId == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "免单配置方案中未配置拼多多联盟");
            }

            //判断输入得是商品id还是商品链接
            if(mdGoodsTurnlinkDto.getItemId().contains("http")){//商品链接
                simpleTurnLinkDto.setUrl(mdGoodsTurnlinkDto.getItemId());
            }else{
                simpleTurnLinkDto.setItemId(mdGoodsTurnlinkDto.getItemId());
            }

            simpleTurnLinkDto.setTokenId(pddTokenId);   //拼多多联盟
            simpleTurnLinkDto.setPddTokenType(0);  //自有账号
            simpleTurnLinkDto.setUseZsUnitUrl(true);
            uzaiRespVo = uzaiTurnlinkFeignService.pddTurnlinkSimple(simpleTurnLinkDto);

            logger.info("---调用拼多多商品转链- 参数={}，返回结果={}",JSONObject.toJSONString(simpleTurnLinkDto),JSONObject.toJSONString(uzaiRespVo));

        }else if(PlatformTypeEnum.PT_DY.getId().intValue() == mdGoodsTurnlinkDto.getPlatform().intValue()) { //抖音
            if(dyTokenId == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "免单配置方案中未配置抖音联盟");
            }
            //判断输入得是商品id还是商品链接
            if(Tools.isInteger(mdGoodsTurnlinkDto.getItemId())){
                simpleTurnLinkDto.setItemId(mdGoodsTurnlinkDto.getItemId());
            }else{
                simpleTurnLinkDto.setPwd(mdGoodsTurnlinkDto.getItemId());
            }

            simpleTurnLinkDto.setTokenId(dyTokenId);
            simpleTurnLinkDto.setDyTokenType(0);  //自有账号
            simpleTurnLinkDto.setUseZsUnitUrl(false);
            uzaiRespVo = uzaiTurnlinkFeignService.dyTurnlinkSimple(simpleTurnLinkDto);

            logger.info("---调用抖音商品转链- 参数={}，返回结果={}",JSONObject.toJSONString(simpleTurnLinkDto),JSONObject.toJSONString(uzaiRespVo));
        }else if(PlatformTypeEnum.PT_KS.getId().intValue() == mdGoodsTurnlinkDto.getPlatform().intValue()) { //快手
            if(ksTlbTokenId == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "免单配置方案中未配置快手推老板共享联盟");
            }
            //判断输入得是商品id还是商品链接
            if(Tools.isInteger(mdGoodsTurnlinkDto.getItemId())){
                simpleTurnLinkDto.setItemId(mdGoodsTurnlinkDto.getItemId());
            }else{
                simpleTurnLinkDto.setPwd(mdGoodsTurnlinkDto.getItemId());
            }

            simpleTurnLinkDto.setTokenId(ksTlbTokenId);
            simpleTurnLinkDto.setDyTokenType(1);  //推老板账号
            simpleTurnLinkDto.setUseZsUnitUrl(false);
            uzaiRespVo = uzaiTurnlinkFeignService.ksTurnlinkSimple(simpleTurnLinkDto);

            logger.info("---调用快手商品转链- 参数={}，返回结果={}",JSONObject.toJSONString(simpleTurnLinkDto),JSONObject.toJSONString(uzaiRespVo));
        }

        if(uzaiRespVo != null && uzaiRespVo.getCode() == 200){
            SimpleTurnlinkVo simpleTurnlinkVo = uzaiRespVo.getData();
            if(simpleTurnlinkVo != null){
                mdGoodsTurnlinkVo.setItemId(simpleTurnlinkVo.getItemId());
                mdGoodsTurnlinkVo.setItemName(simpleTurnlinkVo.getItemName());
                mdGoodsTurnlinkVo.setCouponId(simpleTurnlinkVo.getCouponId());
                mdGoodsTurnlinkVo.setImgs(simpleTurnlinkVo.getImgs());
                //券后价
                Double finalPrice = Tools.getDouble(simpleTurnlinkVo.getFinalPrice());
                mdGoodsTurnlinkVo.setFinalPrice(finalPrice);
                //优惠价
                Double couponVal = Tools.getDouble(simpleTurnlinkVo.getCouponVal());
                mdGoodsTurnlinkVo.setCouponVal(couponVal);
                //原价
                Double price = com.uzai.common.utils.Math.add(finalPrice, couponVal);
                mdGoodsTurnlinkVo.setPrice(price);
            }
        }else{
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "商品转链失败");
        }

        if(StringUtils.isBlank(mdGoodsTurnlinkVo.getItemId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "商品转链失败，未获取到商品id");
        }

        //淘宝商品还需要判断是否参与免单活动商品
        if(PlatformTypeEnum.PT_TAOBAO.getId().intValue() == mdGoodsTurnlinkDto.getPlatform().intValue()) {//淘宝商品
            boolean isMdGoods = false;
            UzaiRespVo<JSONObject> uzaiRespVo_tbInfo = uzaiTurnlinkFeignService.tbItemInfo(mdGoodsTurnlinkVo.getItemId());
            logger.info("---调用查询淘宝商品信息接口- 参数={}，返回结果={}",mdGoodsTurnlinkVo.getItemId(), JSONObject.toJSONString(uzaiRespVo_tbInfo));
            if(uzaiRespVo_tbInfo != null && uzaiRespVo_tbInfo.getCode() == 200) {
                JSONObject jsonObject_tbInfo = uzaiRespVo_tbInfo.getData();
                if(jsonObject_tbInfo != null){
                    JSONObject itemBasicInfo =  jsonObject_tbInfo.getJSONObject("itemBasicInfo");
                    if(itemBasicInfo != null){
                        String materialLibType = Tools.getStr(itemBasicInfo.getString("materialLibType"));
                        String[] materialLibTypeArr = materialLibType.split(",");
                        if(materialLibTypeArr != null && materialLibTypeArr.length > 0){
                            if(ArrayUtils.contains(materialLibTypeArr,"1")){
                                isMdGoods = true;
                            }
                        }
                    }
                }
            }else{
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "调用查询淘宝商品信息接口失败");
            }

            //isMdGoods = true 才能参加免单，否则提示该商品不能添加为免单商品
            if(!isMdGoods){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该淘宝商品不能添加为免单商品");
            }

            //从免单商品优惠券接口中获取最大佣金比例
            try {
                TbPrivilegeDto tbPrivilegeDto = new TbPrivilegeDto();
                tbPrivilegeDto.setItemId(mdGoodsTurnlinkVo.getItemId());
                UzaiRespVo<JSONObject> tbPrivilege = uzaiTurnlinkFeignService.getTbPrivilege(tbPrivilegeDto);
                logger.info("查询免单商品优惠券接口--dto={},result={}",JSONObject.toJSONString(tbPrivilegeDto),JSONObject.toJSONString(tbPrivilege));
                if(tbPrivilege != null && tbPrivilege.getCode() == 200) {
                    JSONObject tbPrivilegesVo = tbPrivilege.getData();
                    if (tbPrivilegesVo != null && tbPrivilegesVo.getJSONObject("result") != null) {
                        JSONObject result = tbPrivilegesVo.getJSONObject("result");
                        if (result != null && result.getJSONObject("data") != null) {
                            JSONObject data = result.getJSONObject("data");
                            if (data != null) {
                                //拿到最大佣金比例
                                Double maxCommissionRate = data.getDouble("maxCommissionRate");
                                mdGoodsTurnlinkVo.setMaxCommissionRate(maxCommissionRate);
                            }
                        }
                    }
                }
            }catch (Exception e){

            }
        }
        return mdGoodsTurnlinkVo;
    }

    /**
     * 获取商品淘口令转链信息
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param mdGoodsTurnlinkDto
     * @return null
     */
    public TbkScTpwdConvertVo tbkScTpwdConvert(MdGoodsPwdConverDto mdGoodsTurnlinkDto){

        TbkScTpwdConvertVo tbkScTpwdConvertVo = new TbkScTpwdConvertVo();

        if(StringUtils.isBlank(mdGoodsTurnlinkDto.getPwd())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "淘口令不存在");
        }

        if(mdGoodsTurnlinkDto.getMdConfigPlanId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请上传免单配置方案id");
        }

        MdConfigPlan mdConfigPlan = mdConfigPlanMapper.selectById(mdGoodsTurnlinkDto.getMdConfigPlanId(), mdGoodsTurnlinkDto.getMerId());
        if(mdConfigPlan == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "选择的免单配置方案不存在");
        }

        Long tbTokenId = null;
        String tbPid = "";

        //淘宝token
        JSONObject jsonObject_tb = JSONObject.parseObject(mdConfigPlan.getData());
        if (jsonObject_tb != null) {
            tbTokenId = jsonObject_tb.getLong("tbTokenId");
            tbPid = jsonObject_tb.getString("tbPid");
        }

        if(tbTokenId == null || StringUtils.isBlank(tbPid)){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "免单配置方案中未配置淘宝联盟和pid");
        }

        TbToken tbToken = tbTokenMapper.selectById(tbTokenId, mdGoodsTurnlinkDto.getMerId());
        if(tbToken == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "免单配置方案中配置淘宝联盟不存在");
        }

        String[] pidArry = tbPid.split("_");
        if(pidArry == null || pidArry.length != 4){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "免单配置方案中配置淘宝联盟pid格式不正确");
        }

        try{
            TbkScTpwdConvertDto tbkScTpwdConvertDto = new TbkScTpwdConvertDto();
            tbkScTpwdConvertDto.setPasswordContent(mdGoodsTurnlinkDto.getPwd());
            tbkScTpwdConvertDto.setAdzoneId(Long.valueOf(pidArry[3]));
            tbkScTpwdConvertDto.setSiteId(Long.valueOf(pidArry[2]));
            tbkScTpwdConvertDto.setSessionKey(tbToken.getAccessToken());
            tbkScTpwdConvertVo = tbApiService.tbkScTpwdConvert(tbkScTpwdConvertDto);
            if(tbkScTpwdConvertVo != null){
                String originPid = Tools.getStr(tbkScTpwdConvertVo.getOriginPid());
                if(originPid.equals(tbPid)){ //传入的pid和返回的pid相等
                    tbkScTpwdConvertVo.setFlag(1);
                }else{
                    tbkScTpwdConvertVo.setFlag(0);
                }
            }
        }catch (Exception e){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "淘口令解析失败");
        }

        return tbkScTpwdConvertVo;
    }

    /**
     * 自动检测免单活动是否下架
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param mdActivity
     * @return null
     */
    public void autoCheckMdGoodsDrop(MdActivity mdActivity){

        if(mdActivity == null){
            return;
        }

        //查询该免单获得的所有商品
        List<MdGoods> mdGoodsList = mdGoodsMapper.findListByActivityId(mdActivity.getId(), mdActivity.getMerId());
        if(mdGoodsList != null && mdGoodsList.size() > 0) {
            for (MdGoods mdGoods : mdGoodsList) {

                //只支持淘宝商品, 不等于淘宝商品，则跳过不执行
                if(Tools.getInteger(mdGoods.getPlatform()).intValue() != PlatformTypeEnum.PT_TAOBAO_VALUE){
                    continue;
                }
                //判断该商品是否开启检测无优惠券自动下架功能
                if(Tools.getInteger(mdGoods.getCheckdrop()).intValue() == 1){ //开启，则调用检测该商品是否有优惠券接口
                    TbPrivilegeDto tbPrivilegeDto = new TbPrivilegeDto();
                    String itemId = mdGoods.getItemId();
                    //判断是否有前缀，如果有，则需要拼接前缀
                    if(StringUtils.isNotBlank(mdGoods.getItemIdPrefix())){
                        itemId = mdGoods.getItemIdPrefix() + "-" + mdGoods.getItemId();
                    }
                    tbPrivilegeDto.setItemId(itemId);
                    UzaiRespVo<JSONObject> tbPrivilege = uzaiTurnlinkFeignService.getTbPrivilege(tbPrivilegeDto);
                    logger.info("查询免单商品优惠券接口--dto={},result={}",JSONObject.toJSONString(tbPrivilegeDto),JSONObject.toJSONString(tbPrivilege));
                    if(tbPrivilege != null && tbPrivilege.getCode() == 200){
                        JSONObject tbPrivilegesVo = tbPrivilege.getData();
                        if(tbPrivilegesVo != null && tbPrivilegesVo.getJSONObject("result") != null){
                            JSONObject result = tbPrivilegesVo.getJSONObject("result");
                            if(result != null && result.getJSONObject("data") != null){
                                JSONObject data = result.getJSONObject("data");
                                if(data != null){
                                    String couponStartTime = data.getString("couponStartTime");
                                    String couponEndTime = data.getString("couponEndTime");
                                    if(StringUtils.isNotBlank(couponStartTime) && StringUtils.isNotBlank(couponEndTime)){
                                        //判断当前时间是否在自动任务开启时间区间内
                                        LocalDateTime couponStartDateTime = LocalDateTime.parse(couponStartTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                                        LocalDateTime couponEndDateTime = LocalDateTime.parse(couponEndTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                                        if(LocalDateTime.now().isAfter(couponStartDateTime) && LocalDateTime.now().isBefore(couponEndDateTime)){
                                            mdGoods.setDropstatus(0); //未下架
                                        }else{
                                            mdGoods.setDropstatus(1); //已下架
                                        }
                                    }else{ //未找到优惠券，则下架该商品
                                        mdGoods.setDropstatus(1); //已下架
                                    }
                                }
                            }
                        }

                        //修改该商品
                        mdGoodsMapper.updateByIdSelective(mdGoods);
                    }
                }

                //判断该商品是否开启检测价格佣金变化自动下架功能
                if(Tools.getInteger(mdGoods.getCheckdropforprice()).intValue() == 1) { //开启，则调用检测该商品价格佣金是否发生变化
                    //如果该商品无券后价或者无最大佣金比例，则跳过不检测
                    if(mdGoods.getFinalPrice() == null || mdGoods.getMaxCommissionRate() == null){
                        continue;
                    }

                    //请求转链最新的商品id
                    MdGoodsTurnlinkDto mdGoodsTurnlinkDto = new MdGoodsTurnlinkDto();
                    mdGoodsTurnlinkDto.setPlatform(Tools.getInteger(mdGoods.getPlatform()));
                    mdGoodsTurnlinkDto.setMerId(mdGoods.getMerId());
                    String itemId = mdGoods.getItemId();
                    if(StringUtils.isNotBlank(mdGoods.getItemIdPrefix())){
                        itemId = mdGoods.getItemIdPrefix() +"-" + mdGoods.getItemId();
                    }
                    mdGoodsTurnlinkDto.setItemId(itemId);
                    mdGoodsTurnlinkDto.setMdConfigPlanId(mdActivity.getConfigId());
                    MdGoodsTurnlinkVo mdGoodsTurnlinkVo = getGoodsTurnlinkInfo(mdGoodsTurnlinkDto);
                    if(mdGoodsTurnlinkVo == null){
                        continue;
                    }

                    if(Tools.getDouble(mdGoodsTurnlinkVo.getFinalPrice()).doubleValue() != Tools.getDouble(mdGoods.getFinalPrice()).doubleValue()
                            || Tools.getDouble(mdGoodsTurnlinkVo.getMaxCommissionRate()).doubleValue() != Tools.getDouble(mdGoods.getMaxCommissionRate()).doubleValue()){
                        mdGoods.setDropstatus(1); //已下架
                        //修改该商品
                        mdGoodsMapper.updateByIdSelective(mdGoods);
                    }
                }
            }
        }
    }

}
